<template>
  <div class="page-container" ref="page">
    <list-searcher
      :searchList="searchList"
      v-model:searchForm="queryParam"
      @submit="handleSubmit"
      @reset="handleReset"
      style="position: relative"
    />
    <div style="position: absolute; top: 25px; left: 25px">
      <a-tooltip content="报表周期可显示前3个月和未来1个月的数据" position="top" mini trigger="click">
        <icon-question-circle style="font-size: 16px" />
      </a-tooltip>
    </div>
    <template v-if="toSearchFlag">
      <a-row style="margin-bottom: 16px">
        <!-- <a-col flex="0 1"> -->
        <div>
          <span style="font-size: 14px; color: #4e5969">车辆总数：</span>
          <span style="font-size: 14px; color: #1890ff">{{ totalData }}</span>
        </div>
        <!-- </a-col> -->
        <a-col flex="auto" style="padding: 0 16px; margin-bottom: 2px">
          <a-alert>如果某一车辆的归属门店进行过多次变更，则该车辆会产生多条数据。</a-alert>
        </a-col>

        <a-col flex="164px">
          <div class="flex">
            <a-button @click="changeToggleStatus">切换报表</a-button>
            <a-button style="margin-left: 16px" type="primary" @click="handleExport">导出</a-button>
          </div>
        </a-col>
      </a-row>
    </template>

    <template v-if="toSearchFlag">
      <a-table :columns="columns" :data="data" v-if="toggleStatus == 0" :pagination="false" :loading="tableLoading">
        <template #carInfo="{ record }">
          <div style="max-width: 240px; min-width: 120px; padding-right: 20px">
            <div>{{ record.licenseNo }}</div>
            <a-tooltip :content="record.modelName">
              <div class="ellipsis-text">{{ record.modelName }}</div>
            </a-tooltip>
          </div>
        </template>

        <template #recordRender="{ record, column }">
          <RecordRender :record="record[column.dataIndex]" />
        </template>
      </a-table>
      <a-row style="margin-top: 24px" v-if="toggleStatus == 0">
        <a-col style="display: flex; justify-content: space-between; align-items: center">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              font-size: 14px;
              font-weight: 400;
              color: #1d2129;
              width: 184px;
            "
            >每页展示
            <a-select
              :options="paginationOptions"
              v-model="pageSelect"
              :allow-clear="false"
              size="small"
              style="width: 70px"
              @change="changePageSelect"
            />
            项结果
          </div>
          <a-pagination :total="totalData" show-total @change="changePagination" v-model:page-size="pageSelect" :current="currentPage" />
        </a-col>
      </a-row>
    </template>
    <!-- 
  <CarRateChart
    :chartXAxisData="chartXAxisData"
    :chartAmountYSeriesData="chartAmountYSeriesData"
    :chartRateYSeriesData="chartRateYSeriesData"
    
    ref="chartDom"
  /> -->
    <div id="myEcharts" ref="my_echarts" v-show="toggleStatus == 1 && toSearchFlag"></div>

    <div class="data-empty" v-if="!toSearchFlag">
      <a-empty> 暂无数据，请选择周期 </a-empty>
    </div>
  </div>
</template>

<script setup name="SiteCarRentalRateList">
  import { ref, reactive, onMounted, computed, nextTick } from 'vue'
  import * as echarts from 'echarts'
  import { graphic } from 'echarts'
  import { siteCarRateList, siteCarRateChart, exportSiteCarRate } from '@/api/reportForms/carRentalRate'
  import { useExport } from '@/hooks/list'
  import { Message } from '@arco-design/web-vue'
  import RecordRender from './components/record-render.vue'

  const toggleStatus = ref(0)
  const pageSelect = ref(10)
  const currentPage = ref(1)
  const tableLoading = ref(false)
  const toSearchFlag = ref(false)

  const chartXAxisData = ref([])
  const chartAmountYSeriesData = ref([])
  const chartRateYSeriesData = ref([])

  const paginationOptions = reactive([
    { value: 10, label: '10' },
    { value: 20, label: '20' },
    { value: 50, label: '50' },
  ])

  // 查询条件
  const searchList = computed(() => {
    return [
      {
        label: '报表周期',
        prop: 'queryDate',
        type: 'i-range-picker',
        // disabledDate: (current) => {
        //   const today = dayjs().startOf('day')
        //   const cur = dayjs(current)
        //   return cur.isBefore(today.subtract(3, 'month')) || cur.isAfter(today.add(1, 'month'))
        // },
        change: (value = []) => {
          queryParam.startDate = value[0]
          queryParam.endDate = value[1]
        },
      },
      {
        label: '归属门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
        },
        change: () => {
          queryParam.carId = undefined
        },
      },
      {
        label: '车牌号',
        prop: 'carId',
        type: 'remote-select',
        attrs: {
          type: 'car_licenseno_list',
          params: {
            siteIdList: queryParam.siteIdList,
            operateStatusList: [10, 20, 30, 40, 50, 60],
            ifNotDel: false,
          },
        },
      },
    ]
  })

  const queryParam = reactive({
    pageSize: 10,
    pageNumber: 1,
    siteIdList: [],
    queryDate: [],
  })

  const totalData = ref(0)

  // table 配置
  const columns = ref([
    { title: '车辆信息', dataIndex: 'licenseNo', slotName: 'carInfo', width: 240 },
    { title: '车辆来源', dataIndex: 'sourceName', width: 100 },
    { title: '归属门店', dataIndex: 'siteName', width: 150 },
    { title: '可租天数', unit: '天', dataIndex: 'canRentDays', width: 110 },
    { title: '租日', unit: '天', dataIndex: 'rentDays', width: 100 },
    { title: '总收益', unit: '天', dataIndex: 'totalAmount', width: 110 },
    { title: '平均出租率', dataIndex: 'avgRateStr', width: 120 },
  ])

  const data = ref([])

  const tooltipItemsHtmlString = (items) => {
    return items
      .map(
        (el) => `<div class="content-panel" style="display: flex;
          justify-content: space-between;width: 100%;
          padding: 0 9px;
          background: rgba(255, 255, 255, 0.8);
          height: 32px;
          line-height: 32px;
          box-shadow: 6px 0px 20px rgba(34, 87, 188, 0.1);
          border-radius: 4px;
          margin-bottom: 4px;">
              <p style="margin: 0;padding: 0;">
                <span style="background-color: ${el.color};display: inline-block;
          margin-right: 8px;
          width: 10px;
          height: 10px;
          border-radius: 50%;" ></span>
          <span>${el.seriesName}</span>
        </p>
        <span style="font-size: 13px;
          line-height: 15px;
          display: flex;
          align-items: center;
          text-align: right;
          color: #1d2129;
          font-weight: bold;margin-left:8px;">
        ${el.value} ${el.seriesType == 'line' ? '%' : '元'}
          </span>
        </div>`
      )
      .join('')
  }

  function graphicFactory(side) {
    return {
      type: 'text',
      bottom: '8',
      ...side,
      style: {
        text: '',
        textAlign: 'center',
        fill: '#4E5969',
        fontSize: 12,
      },
    }
  }
  const graphicElements = ref([graphicFactory({ left: '2.6%' }), graphicFactory({ right: 0 })])
  const colors = reactive(['#246EFF'])
  const myEcharts = echarts

  const initChart = () => {
    let chart = myEcharts.init(document.getElementById('myEcharts'))
    chart.setOption(
      {
        color: colors,
        grid: {
          // left: '40',
          // right: 0,
          // top: '20',
          bottom: '100',
        },
        tooltip: {
          show: true,
          trigger: 'axis',
          formatter(params) {
            // console.log(params)
            let firstElement = {}
            params.forEach((item) => {
              firstElement = {
                axisDim: item.axisDim,
                axisIndex: item.axisIndex,
                axisType: item.axisType,
                axisId: item.axisId,
                axisValue: item.axisValue,
                axisValueLabel: item.axisValueLabel,
              }
            })
            return `<div style="background: linear-gradient(
              304.17deg,
              rgba(253, 254, 255, 0.6) -6.04%,
              rgba(244, 247, 252, 0.6) 85.2%
            ) !important;margin:-10px;padding:10px;">
                      <p style="font-size: 13px;
              line-height: 15px;
              display: flex;
              align-items: center;
              text-align: right;
              color: #1d2129;
              font-weight: bold;margin:0;padding:0;margin-bottom:8px;">${firstElement.axisValueLabel}</p>
                ${tooltipItemsHtmlString(params)}
              </div>`
          },
          className: 'echarts-tooltip-diy2',
        },
        legend: {
          bottom: 0,
          data: ['车辆出租率', '车辆日租价'],
          icon: 'circle',
          textStyle: {
            color: '#4E5969',
          },
        },
        graphic: {
          elements: graphicElements.value,
        },
        dataZoom: [
          {
            bottom: 40,
            type: 'slider',
            left: 40,
            right: 14,
            height: 14,
            borderColor: 'transparent',
            handleIcon:
              'image://http://p3-armor.byteimg.com/tos-cn-i-49unhts6dw/1ee5a8c6142b2bcf47d2a9f084096447.svg~tplv-49unhts6dw-image.image',
            handleSize: '20',
            handleStyle: {
              shadowColor: 'rgba(0, 0, 0, 0.2)',
              shadowBlur: 4,
            },
            brushSelect: false,
            backgroundColor: '#F2F3F5',
          },
          {
            type: 'inside',
            start: 0,
            end: 100,
            zoomOnMouseWheel: false,
          },
        ],
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true,
            },
            // prettier-ignore
            data: chartXAxisData.value,
            axisPointer: {
              show: true,
              lineStyle: {
                color: '#23ADFF',
                width: 2,
              },
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '车辆出租率(%)',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: false,
              // lineStyle: {
              //   color: '#4E5969',
              // },
            },
            axisLabel: {
              formatter: '{value}',
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                color: '#E5E8EF',
              },
            },
          },
          {
            type: 'value',
            name: '车辆日租价(元)',
            position: 'right',
            alignTicks: true,
            axisLine: {
              show: false,
              lineStyle: {
                color: '#4E5969',
              },
            },
            axisLabel: {
              formatter: '{value}',
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                color: '#E5E8EF',
              },
            },
          },
        ],
        series: [
          {
            name: '车辆出租率',
            data: chartRateYSeriesData.value,
            type: 'line',
            smooth: true,
            // symbol: 'circle',
            symbolSize: 12,
            emphasis: {
              focus: 'series',
              itemStyle: {
                borderWidth: 2,
              },
            },
            lineStyle: {
              width: 3,
              color: new graphic.LinearGradient(0, 0, 1, 0, [
                {
                  offset: 0,
                  color: 'rgba(30, 231, 255, 1)',
                },
                {
                  offset: 0.5,
                  color: 'rgba(36, 154, 255, 1)',
                },
                {
                  offset: 1,
                  color: 'rgba(111, 66, 251, 1)',
                },
              ]),
            },
            showSymbol: false,
            // 区域填充样式
            areaStyle: {
              opacity: 0.8,
              color: new graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(17, 126, 255, 0.16)',
                },
                {
                  offset: 1,
                  color: 'rgba(17, 128, 255, 0)',
                },
              ]),
            },
          },
          {
            name: '车辆日租价',
            type: 'bar',
            yAxisIndex: 1,
            data: chartAmountYSeriesData.value,
            emphasis: {
              focus: 'series',
              itemStyle: {
                borderWidth: 2,
                borderColor: '#E0E3FF',
              },
            },
          },
        ],
      },
      true
    )

    window.onresize = function () {
      chart.resize()
    }
  }
  // 导出事件
  const handleExport = () => {
    useExport(exportSiteCarRate, queryParam)
  }

  const my_echarts = ref(null)
  //切换报表
  const changeToggleStatus = () => {
    if (toggleStatus.value == 0) {
      toggleStatus.value = 1
      myEcharts.dispose
      getChartList()
    } else {
      queryParam.pageNumber = 1
      getDataList()
      toggleStatus.value = 0
    }
  }

  /**
   * 获取图表
   */
  const getChartList = () => {
    siteCarRateChart({
      siteIdList: queryParam.siteIdList,
      startDate: queryParam.startDate,
      endDate: queryParam.endDate,
      carId: queryParam.carId,
      reportType: 5,
    }).then((res) => {
      if (res.code == 200) {
        chartXAxisData.value = []
        chartAmountYSeriesData.value = []
        chartRateYSeriesData.value = []
        const result = res.result
        if (result.amountList.length) {
          result.amountList.forEach((item) => {
            chartXAxisData.value.push(item.date)
            chartAmountYSeriesData.value.push(item.data)
          })
        }
        if (result.rateList.length) {
          result.rateList.forEach((item) => {
            chartRateYSeriesData.value.push(item.data)
          })
        }
        initChart()
      }
    })
  }

  /**
   * 切换分页
   */
  const changePagination = (e) => {
    queryParam.pageNumber = e
    currentPage.value = e
    handleSubmit('pageNumber')
  }

  /**
   * 切换每页展示个数
   */
  const changePageSelect = (e) => {
    console.log(e)
    queryParam.pageSize = e
    handleSubmit('pageSize')
  }

  //重置
  const handleReset = () => {
    data.value = []
    toggleStatus.value = 0
    toSearchFlag.value = false
  }

  /**
   * 查询列表/图表
   * toggleStatus.value = 0 查询列表
   * toggleStatus.value = 1 查询图表
   */
  const handleSubmit = (e) => {
    if (!queryParam.queryDate || queryParam.queryDate.length == 0) {
      Message.warning('请选择报表周期后查询')
      return
    }
    if (!e || e == 'pageSize') {
      queryParam.pageNumber = 1
      currentPage.value = 1
    }
    if (toggleStatus.value == 0) {
      getDataList()
    } else {
      getChartList()
    }
  }
  const tableMinWidth = computed(() => {
    return columns.value.length * 120
  })
  const page = ref(null)

  /**
   * 查询列表
   */
  const getDataList = () => {
    toSearchFlag.value = true
    tableLoading.value = true
    siteCarRateList({ ...queryParam }).then(async (res) => {
      tableLoading.value = false
      if (res.code == 200) {
        data.value = []
        columns.value = columns.value.slice(0, 7)
        await nextTick()
        const result = res.result.data
        if (result.length > 0) {
          result.forEach((item) => {
            let dateTimeList = item.data
            if (Array.isArray(dateTimeList) && dateTimeList.length > 0) {
              dateTimeList.forEach((dateTimeItem, index) => {
                item[`dataTime${index}`] = dateTimeItem || {}
              })
            }
          })
          data.value = result
          totalData.value = res.result.total
          const date = result[0].data
          date.forEach((item, index) => {
            columns.value.push({
              width: 120,
              title: item.date,
              align: 'left',
              dataIndex: 'dataTime' + index,
              slotName: 'recordRender',
            })
          })
          if (tableMinWidth.value < page.value.clientWidth) {
            columns.value.push({
              title: '',
              dataIndex: 'dataTime--1',
            })
          }
        }
      }
    })
  }
  onMounted(() => {
    initChart()
  })
</script>

<style lang="less" scoped>
  #myEcharts {
    width: calc(100vw - 300px);
    height: 400px;
  }
  .echarts-tooltip-diy {
    background: linear-gradient(304.17deg, rgba(253, 254, 255, 0.6) -6.04%, rgba(244, 247, 252, 0.6) 85.2%) !important;
    border: none !important;
    backdrop-filter: blur(10px) !important;
    /* Note: backdrop-filter has minimal browser support */

    border-radius: 6px !important;
    .content-panel {
      display: flex;
      justify-content: space-between;
      padding: 0 9px;
      background: rgba(255, 255, 255, 0.8);
      width: 164px;
      height: 32px;
      line-height: 32px;
      box-shadow: 6px 0px 20px rgba(34, 87, 188, 0.1);
      border-radius: 4px;
      margin-bottom: 4px;
    }
    .tooltip-title {
      margin: 0 0 10px 0;
    }
    p {
      margin: 0;
    }
    .tooltip-title,
    .tooltip-value {
      font-size: 13px;
      line-height: 15px;
      display: flex;
      align-items: center;
      text-align: right;
      color: #1d2129;
      font-weight: bold;
    }
    .tooltip-item-icon {
      display: inline-block;
      margin-right: 8px;
      width: 10px;
      height: 10px;
      border-radius: 50%;
    }
  }
  .ellipsis-text {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
  .data-empty {
    margin-top: 100px;
  }
  :deep(.arco-pagination-options) {
    display: none;
  }
  :deep(.arco-alert) {
    padding: 4px 15px;
  }
</style>
